package com.zidongxiangxi.rabbit.producer.sql;

import org.springframework.util.StringUtils;

/**
 * 发送端sql提供类
 *
 * @author chenxudong
 * @date 2020/11/07
 */
public class ProducerSqlProvider {
	private static final String DEFAULT_TABLE_NAME = "producer";
	private static final String INSERT_SQL = "insert into %s (application, host, port, virtual_host, "
			+ "type, exchange, routing_key, message_id, message, send_status, max_retry_times, next_retry_time)"
			+ " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
	private static final String SELECT_SQL = "select  * from %s where application=? and message_id=?";
	private static final String SENDING_SQL = "update %s set send_status=1, retry_times=?, next_retry_time=? where "
			+ "application=? and message_id=?";
	private static final String FAIL_SQL = "update %s set send_status=2, retry_times=max_retry_times where application=? "
			+ "and message_id=?";
	private static final String DELETE_SQL = "delete from %s where application=? and message_id=?";
	private static final String LIST_SENDING_SQL = "select * from %s where send_status=1 and next_retry_time < now() "
			+ "and application=? order by next_retry_time limit ?, ?";

	private final String insertSql, selectSql, sendingSql, failSql, deleteSql, listSendingSql;

	public ProducerSqlProvider() {
		this(DEFAULT_TABLE_NAME);
	}

	public ProducerSqlProvider(String tableName) {
		tableName = StringUtils.isEmpty(tableName) ? DEFAULT_TABLE_NAME : tableName;
		insertSql = String.format(INSERT_SQL, tableName);
		selectSql = String.format(SELECT_SQL, tableName);
		sendingSql = String.format(SENDING_SQL, tableName);
		failSql = String.format(FAIL_SQL, tableName);
		deleteSql = String.format(DELETE_SQL, tableName);
		listSendingSql = String.format(LIST_SENDING_SQL, tableName);
	}

	public String getInsertMqSql() {
		return insertSql;
	}

	public String getSelectMqSql() {
		return selectSql;
	}

	public String getSendingMqSql() {
		return sendingSql;
	}

	public String getFailMqSql() {
		return failSql;
	}

	public String getDeleteMqSql() {
		return deleteSql;
	}

	public String getListSendingMqSql() {
		return listSendingSql;
	}
}
